<?php
namespace App\Controllers;

use App\Models\SystemModel;
use App\Models\UserModel;
/**
 * Class BaseController
 *
 * BaseController provides a convenient place for loading components
 * and performing functions that are needed by all your controllers.
 * Extend this class in any new controllers:
 *     class Home extends BaseController
 *
 * For security be sure to declare any new methods as protected or private.
 */

use CodeIgniter\Controller;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

class BaseController extends Controller
{
    /**
     * An array of helpers to be loaded automatically upon
     * class instantiation. These helpers will be available
     * to all other controllers that extend BaseController.
     *
     * @var array
     */
    protected $helpers = ['cookie', 'security', 'filesystem', 'ams'];
    protected $renderer;
    protected $cache;
    protected $request;
    protected $response;
    protected $session;
    protected $ilocks;
    protected $agent;

    protected $systemModel;
    protected $userModel;

    protected $admin;
    protected $adminid;
    protected $user;
    protected $userid;

    public $siteinfo;
    public $uri;
    public $uripath;

    /**
     * Constructor.
     *
     * @param RequestInterface  $request
     * @param ResponseInterface $response
     * @param LoggerInterface   $logger
     */
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        // Do Not Edit This Line
        parent::initController($request, $response, $logger);

        //--------------------------------------------------------------------
        // Preload any models, libraries, etc, here.
        //--------------------------------------------------------------------
        // E.g.: $this->session = \Config\Services::session();

        $this->session = \Config\Services::session();
        $this->uri = $uri = $this->request->uri->getSegments();
        $this->renderer = \Config\Services::renderer();
        $this->agent = $this->request->getUserAgent();

        if ($this->uri) {
            $this->uripath = implode('/', $this->uri);
        } else {
            $this->uripath = '/';
        }

        //是否安装(installed)?
        $this->ilocks = WRITEPATH . 'install.locks';
        if (!is_file($this->ilocks) && ((isset($uri[0]) && $uri[0] != 'install') || !isset($uri[0]))) {
            header('Location:/install');
            exit();
        }

        //初始化系统前(before init event)
        \CodeIgniter\Events\Events::trigger('ciams_base_init_before');

        $this->systemModel = new SystemModel();

        define('IS_AJAX', (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest'));
        define('IS_POST', (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] == 'POST') && isset($_POST) && is_array($_POST));
        define('IS_AJAX_POST', IS_POST);

        //**********站点信息(siteinfo)*************//
        $domainfile = WRITEPATH . 'config/domains.php';
        if (is_file($domainfile)) {
            $domain = require $domainfile;
        } else {
            $domain = [];
        }
        $sitefile = WRITEPATH . 'config/site.php';
        if (is_file($sitefile)) {
            $site = require $sitefile;
        } else {
            $site = [];
        }

        if (defined('MODDIR') && MODDIR && !is_file(WRITEPATH . 'module/' . MODDIR . '.lock')) {
            $this->goTo404('页面未找到');
        }

        $this->siteinfo = $site;
        foreach ($site as $var => $value) {
            !defined($var) && define($var, $value);
        }

        $this->siteinfo['SITE_PC'] = $this->siteinfo['SITE_URL'] = $site['SITE_URL'] = ams_http_prefix(($site['SITE_DOMAIN'] ? $site['SITE_DOMAIN'] : DOMAIN_NAME) . '/');
        $this->siteinfo['SITE_MURL'] = ams_http_prefix((isset($site['SITE_MOBILE']) ? $site['SITE_MOBILE'] : DOMAIN_NAME) . '/');

        // 识别移动端
        if ($this->agent->isMobile() && $this->siteinfo['SITE_MOBILE_OPEN']) {
            $this->siteinfo['SITE_PC'] = $this->siteinfo['SITE_URL'];
            $this->siteinfo['SITE_MOBILE'] = true;
        }

        // 站点或系统信息
        if (isset($domain[DOMAIN_NAME])) {
            $orthers = @explode(',', $this->siteinfo['SITE_DOMAINS']);
            $this->siteinfo['SITE_M_URL'] = $this->siteinfo['SITE_PC'] = $this->siteinfo['SITE_URL']; // PC端为主域名
            $uri = isset($_SERVER['HTTP_X_REWRITE_URL']) && trim($_SERVER['REQUEST_URI'], '/') == SELF ? trim($_SERVER['HTTP_X_REWRITE_URL'], '/') : ($_SERVER['REQUEST_URI'] ? trim($_SERVER['REQUEST_URI'], '/') : '');
            if ($orthers && DOMAIN_NAME != $this->siteinfo['SITE_DOMAIN'] && in_array(DOMAIN_NAME, $orthers)) {
                // 判断当前域名为“其他域名”
                // 301 转向开启
                defined('SITE_URL_301') && SITE_URL_301 && redirect(ams_http_prefix($this->siteinfo['SITE_DOMAIN'] . '/' . $uri), '', '301');
                $this->siteinfo['SITE_PC'] = $this->siteinfo['SITE_URL'] = ams_http_prefix(DOMAIN_NAME . '/');
            } elseif (isset($this->siteinfo['SITE_MOBILE']) && $this->siteinfo['SITE_MOBILE']) {
                // 当前网站存在移动端域名时
                if (DOMAIN_NAME == $this->siteinfo['SITE_MOBILE']) {
                    // 当此域名是移动端域名时重新赋值给主站URL
                    $this->siteinfo['SITE_URL'] = ams_http_prefix(DOMAIN_NAME . '/');
                    $this->siteinfo['SITE_MOBILE'] = true;
                } elseif (
                    $this->agent->isMobile()
                    && $this->siteinfo['SITE_MOBILE_OPEN']
                    && $this->siteinfo['SITE_MOBILE']
                    && DOMAIN_NAME == $this->siteinfo['SITE_DOMAIN']
                    && !IS_ADMIN
                ) {
                    // 当网站开启强制定向时，并且存在移动端域名、URL是主站的域名、非后台
                    redirect(ams_http_prefix($this->siteinfo['SITE_MOBILE'] . '/' . $uri), '', '301');
                    exit;
                }
            } elseif ($this->agent->isMobile() && $this->siteinfo['SITE_MOBILE_OPEN'] == 1) {
                // 识别移动端
                $this->siteinfo['SITE_MOBILE'] = true;
            }
        }

        // 默认文件上传目录
        $this->siteinfo['SITE_UPLOAD_DIR'] = 'uploads';
        $this->siteinfo['SITE_UPLOAD_PATH'] = WEBPATH . 'writable/' . $this->siteinfo['SITE_UPLOAD_DIR'];
        $this->siteinfo['SITE_ATTACHMENT_URL'] = $this->siteinfo['SITE_URL'] . 'writable/' . $this->siteinfo['SITE_UPLOAD_DIR'];
        $this->siteinfo['SITE_ATTACHMENT_URL'] = trim($this->siteinfo['SITE_ATTACHMENT_URL'], '/') . '/';
        $this->siteinfo['UEDITOR_IMG_ID'] = md5($this->siteinfo['SITE_ATTACHMENT_URL']); // 编辑器附件ID

        //初始化系统(init system)
        \CodeIgniter\Events\Events::trigger('ciams_base_init');

        //常量便于全局使用
        foreach ($this->siteinfo as $var => $value) {
            if ($var == 'SITE_MOBILE' && $value === true && IS_ADMIN) {
                $value = '';
            } elseif (strpos($value, 'SITE_CACHE') === 0) {
                $value = (int) $value;
            }
            !defined($var) && define($var, $value); // 定义站点常量
        }

        define('THEME_PATH', SITE_URL . 'public/'); //系统风格
        define('HOME_THEME_PATH', SITE_URL . 'public/theme/'); //站点前端风格
        if (!defined('IS_MOBILE') && $this->agent->isMobile()) {
            define('IS_MOBILE', 1);
        }

        $this->renderer->setData(['siteinfo' => $this->siteinfo, 'uri' => $this->uri, 'uripath' => $this->uripath]);

        //初始化系统后(before init event)
        \CodeIgniter\Events\Events::trigger('ciams_base_init_after');


    }

    protected function goTo404($msg = '')
    {
        throw new \Exception($msg, '404');
        exit();
    }

    public function xss_clean($str, $level = false)
    {
        $xss = new \App\Libraries\Xss();
        $str = $xss->xss_clean($str, $level);
        return $str;
    }

    public function set_cookie($name, $value = '', $expire = '')
    {
        $response = \Config\Services::response(null, true);
        $response->setCookie($name, $value, $expire);
    }

    //图形验证码 $id 表单的 name
    public function check_captcha($id = '')
    {
        if (!$id) {
            return false;
        }
        $data = $this->request->getPost($id);
        $code = $this->session->get('amscaptcha');
        if (strtolower($data) == $code && $code) {
            $this->session->remove('amscaptcha');
            return true;
        }
    }

    public function checkRandCaptcha($id = '')
    {
        if (!$id) {
            return false;
        }
        $data = $this->request->getPost($id);
        $code = $this->session->get('randcha');
        if (strtolower($data) == $code && $code) {
            $this->session->remove('randcha');
            return true;
        }
    }

    public function _json($code = 1, $msg = '', $data = null)
    {
        if (is_array($code)) {
            echo json_encode($code);
        } else {
            echo json_encode(ams_rt($code, $msg, $data));
        }
        exit;
    }

    //提示消息
    public function msg($code, $msg, $data = [])
    {
        $time = isset($data['time']) ? intval($data['time']) : 3; //默认3秒跳转
        if (isset($data['url']) && $data['url']) {
            $backurl = $this->xss_clean($data['url']);
            if (strpos($backurl, '?backurl=') !== false) {
                $arr = explode('?backurl=', $backurl);
                if (isset($arr[1]) && $arr[1]) {
                    $backurl = $arr[0] . '?backurl=' . urlencode($arr[1]);
                }
            }
        } else if (isset($_SERVER['HTTP_REFERER']) && strpos($_SERVER['HTTP_REFERER'], 'php?') !== false) {
            $backurl = $this->xss_clean($_SERVER['HTTP_REFERER']);
        }

        if (!isset($backurl) || !$backurl) {
            $backurl = '/';
        }

        if ($this->request->getGet('is_ajax') || IS_AJAX || $this->request->isAJAX()) {
            $this->_json($code, $msg, $data);
            exit();
        }

        $vdata = [
            'code' => $code,
            'msg' => $msg,
            'url' => $backurl,
            'time' => $time,
            'mark' => $code,
        ];
        echo view('msg.html', $vdata);
        exit();
    }


}
